#include "patient_chatlistwidget.h"
#include "ui_patient_chatlistwidget.h"
#include "../../network/networkclient.h"
#include "../common/chatwindow.h"
#include "../common/doctordetailwidget.h"
#include <QJsonObject>
#include <QJsonArray>
#include <QPushButton>
#include <QMessageBox>
#include <QDebug>

PatientChatListWidget::PatientChatListWidget(int patientId, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PatientChatListWidget),
    m_patientId(patientId)
{
    ui->setupUi(this);
    
    // 设置表格
    ui->doctorTable->setColumnCount(6);
    ui->doctorTable->setHorizontalHeaderLabels({"医生ID", "姓名", "科室", "职称", "门诊类型", "操作"});
    ui->doctorTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->doctorTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->doctorTable->horizontalHeader()->setStretchLastSection(false);
    ui->doctorTable->setColumnWidth(0, 80);
    ui->doctorTable->verticalHeader()->setDefaultSectionSize(40);
    ui->doctorTable->setColumnWidth(1, 100);
    ui->doctorTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch);
    ui->doctorTable->setColumnWidth(3, 120);
    ui->doctorTable->setColumnWidth(4, 100);
    ui->doctorTable->setColumnWidth(5, 120); // 操作列加宽
    
    // 隐藏行号列避免乱码
    ui->doctorTable->verticalHeader()->setVisible(false);
    
    // 连接网络消息
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &PatientChatListWidget::onMessageReceived);
    
    // 加载部门和医生
    loadDepartments();
    loadDoctors();
}

PatientChatListWidget::~PatientChatListWidget()
{
    delete ui;
}

void PatientChatListWidget::loadDepartments() {
    NetworkClient::instance().sendRequest(MSG_GET_DEPARTMENTS, QJsonObject());
}

void PatientChatListWidget::loadDoctors() {
    qDebug() << "患者端 - 请求获取所有医生";
    QJsonObject request;
    request["department_id"] = 0; // 0表示所有部门
    NetworkClient::instance().sendRequest(MSG_GET_ALL_DOCTORS, request);
}

void PatientChatListWidget::filterDoctors() {
    // 根据当前选择的科室、门诊类型和搜索关键字过滤医生
    QList<Doctor> filteredDoctors;
    
    int deptId = ui->departmentCombo->currentData().toInt();
    QString clinicType = ui->clinicTypeCombo->currentText();
    QString searchName = ui->doctorNameEdit->text().trimmed();
    
    for (const Doctor& doctor : m_doctors) {
        // 科室筛选
        if (deptId > 0 && doctor.departmentId != deptId) {
            continue;
        }
        
        // 门诊类型筛选
        if (clinicType != "全部" && doctor.clinicType != clinicType) {
            continue;
        }
        
        // 姓名搜索
        if (!searchName.isEmpty() && !doctor.realName.contains(searchName)) {
            continue;
        }
        
        filteredDoctors.append(doctor);
    }
    
    // 更新表格（使用过滤后的列表）
    ui->doctorTable->setRowCount(filteredDoctors.size());
    
    for (int i = 0; i < filteredDoctors.size(); ++i) {
        const Doctor& doctor = filteredDoctors.at(i);
        
        ui->doctorTable->setItem(i, 0, new QTableWidgetItem(QString::number(doctor.id)));
        ui->doctorTable->setItem(i, 1, new QTableWidgetItem(doctor.realName));
        ui->doctorTable->setItem(i, 2, new QTableWidgetItem(doctor.departmentName));
        ui->doctorTable->setItem(i, 3, new QTableWidgetItem(doctor.title));
        ui->doctorTable->setItem(i, 4, new QTableWidgetItem(doctor.clinicType));
        
        // 添加"沟通"按钮
        // 创建按钮容器实现居中
        QPushButton* chatBtn = new QPushButton("沟通");
        chatBtn->setMinimumHeight(30);
        chatBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        chatBtn->setProperty("doctorId", doctor.id);
        chatBtn->setProperty("doctorName", doctor.realName);
        connect(chatBtn, &QPushButton::clicked, this, &PatientChatListWidget::onChatButtonClicked);
        
        ui->doctorTable->setCellWidget(i, 5, chatBtn);
    }
}

void PatientChatListWidget::updateDoctorTable() {
    filterDoctors(); // 直接使用过滤功能
}

void PatientChatListWidget::showDoctorDetail(int doctorId) {
    // 找到对应的医生
    Doctor selectedDoctor;
    bool found = false;
    for (const Doctor& doctor : m_doctors) {
        if (doctor.id == doctorId) {
            selectedDoctor = doctor;
            found = true;
            break;
        }
    }
    
    if (found) {
        DoctorDetailWidget* detailWidget = new DoctorDetailWidget(selectedDoctor, this);
        detailWidget->setWindowModality(Qt::ApplicationModal);
        detailWidget->show();
    }
}

void PatientChatListWidget::openChatWindow(int doctorId, const QString& doctorName) {
    // 查找医生信息，获取职称和科室
    QString doctorInfo = "";
    for (const Doctor& doctor : m_doctors) {
        if (doctor.id == doctorId) {
            doctorInfo = doctor.title + " | " + doctor.departmentName;
            break;
        }
    }
    
    ChatWindow* chatWindow = new ChatWindow(m_patientId, doctorId, doctorName, doctorInfo, this);
    chatWindow->setWindowModality(Qt::ApplicationModal);
    chatWindow->show();
}

void PatientChatListWidget::on_departmentCombo_currentIndexChanged(int index) {
    Q_UNUSED(index);
    filterDoctors();
}

void PatientChatListWidget::on_clinicTypeCombo_currentIndexChanged(int index) {
    Q_UNUSED(index);
    filterDoctors();
}

void PatientChatListWidget::on_searchButton_clicked() {
    filterDoctors();
}

void PatientChatListWidget::on_doctorTable_cellDoubleClicked(int row, int column) {
    Q_UNUSED(column);
    
    int doctorId = ui->doctorTable->item(row, 0)->text().toInt();
    showDoctorDetail(doctorId);
}

void PatientChatListWidget::onChatButtonClicked() {
    QPushButton* btn = qobject_cast<QPushButton*>(sender());
    if (btn) {
        int doctorId = btn->property("doctorId").toInt();
        QString doctorName = btn->property("doctorName").toString();
        openChatWindow(doctorId, doctorName);
    }
}

void PatientChatListWidget::onMessageReceived(MessageType type, const QJsonObject& data) {
    if (type == MSG_GET_DEPARTMENTS_RESPONSE) {
        if (data["success"].toBool()) {
            ui->departmentCombo->clear();
            ui->departmentCombo->addItem("全部", 0);
            
            QJsonArray depts = data["departments"].toArray();
            for (const QJsonValue& value : depts) {
                QJsonObject deptObj = value.toObject();
                ui->departmentCombo->addItem(deptObj["name"].toString(), deptObj["id"].toInt());
            }
        }
    }
    else if (type == MSG_GET_ALL_DOCTORS_RESPONSE) {
        qDebug() << "患者端 - 收到医生列表响应";
        qDebug() << "  成功:" << data["success"].toBool();
        if (data["success"].toBool()) {
            m_doctors.clear();
            QJsonArray doctorsArray = data["doctors"].toArray();
            qDebug() << "  医生数量:" << doctorsArray.size();
            for (const QJsonValue& value : doctorsArray) {
                Doctor doctor = Doctor::fromJson(value.toObject());
                m_doctors.append(doctor);
                qDebug() << "    医生:" << doctor.realName << "科室:" << doctor.departmentName;
            }
            updateDoctorTable();
        } else {
            qDebug() << "  错误信息:" << data["message"].toString();
        }
    }
}

